package homework;

public class demo6 {
    private static Object locker = new Object();
    private static int state = 0;
    private static int count = 10;
    public static void main(String[] args) {
        Thread t1 = new Thread(()->{
           synchronized(locker) {
            for (int i = 0; i < count; i++) {
                //等待轮到打印A
                while (state != 0) {
                    try {
                        locker.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                System.out.print("A");
                state = 1;
                //通知其他线程
                locker.notifyAll();
            }
           }
            
        });
        Thread t2 = new Thread(()->{
            synchronized(locker){
                for (int i = 0; i < count; i++) {
                    while (state != 1) {
                        try {
                            locker.wait();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    System.out.print("B");
                    state = 2;
                    //通知其他线程
                    locker.notifyAll();
                }
            }
        });
        Thread t3 = new Thread(()->{
             synchronized(locker){
                for (int i = 0; i < count; i++) {
                    while (state != 2) {
                        try {
                            locker.wait();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    System.out.println("C");
                    state = 0;
                    //通知其他线程
                    locker.notifyAll();
                }
            }
        });

        t1.start();
        t2.start();
        t3.start();
    }
}
